package com.hevs.samplewebapp.client.services;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.user.client.Window;
import com.hevs.samplewebapp.client.Administration;
import com.hevs.samplewebapp.client.bean.CompositeWRefresh;
import com.hevs.samplewebapp.client.bean.FakeSyncRestCall;
import com.hevs.samplewebapp.client.bean.JSONHelper;
import com.hevs.samplewebapp.client.bean.User;
import com.hevs.samplewebapp.client.bean.UserDataJson;
import com.hevs.samplewebapp.client.dialogbox.ServerResponseMessages;

/**
 * Implementation of the User management service Interface.
 * 
 * @author Thomas Rouvinez
 * @Date: 23.04.2012
 *
 */
public class UserAdministrationServiceImpl implements UserAdministrationService{
	// Variables.
	/**
	 * List of users
	 */
	private List<User> userList =  new ArrayList<User>();

	// -----------------------------------------------------------------
	// Get users' list.	
	// -----------------------------------------------------------------

	@Override
	/**
	 * Method to retrieve the list of users from the server
	 */
	public void getUsers(CompositeWRefresh comp) {
		String url = Administration.JSON_URL_ADMIN;
		url = URL.encode(url);
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		
		try {
			@SuppressWarnings("unused")
			Request request = builder.sendRequest(null, new FakeSyncRestCall(comp) {
				
				public void onError(Request request, Throwable exception) {
					Window.alert("Error while refreshing user list");
				}

				public void onResponseReceived(Request request, Response response) {
					if(200 == response.getStatusCode()){
						// Get new list of users.
						convertJSToListUser(JSONHelper.asArrayOfUserData(response.getText()));
						refresh();
					}else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		} catch (Exception e) {
			Window.alert("Error while refreshing user list");
		}
	}

	/**
	 * Getter for the users list
	 * @return
	 * a list of users
	 */
	public List<User> getUserSet(){
		return this.userList;
	}

	// -----------------------------------------------------------------
	// Update a user.
	// -----------------------------------------------------------------

	/**
	 * Method to create a user
	 */
	public void create(JSONObject userBeforeCreation){
		String url = Administration.JSON_URL_ADMIN;
		url = URL.encode(url);
		RequestBuilder builder = new RequestBuilder(RequestBuilder.PUT,url);

		// Make the actual server call.
		try {
				@SuppressWarnings("unused")
				Request request = builder.sendRequest(userBeforeCreation.toString(), new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					Window.alert("Error while creating a new user");
				}

				public void onResponseReceived(Request request, Response response) {
					if(200 == response.getStatusCode()){
						Window.alert("User created!");
					}else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		} catch (Exception e) {
			Window.alert("Error while creating a new user");
		}		
	}
	
	@Override
	/**
	 * Method to update a user
	 */
	public void update(JSONObject userBeforeUpdate) {
		String url = Administration.JSON_URL_ADMIN;
		url = URL.encode(url);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.PUT,url);

		// Make the actual server call.
		try {
			@SuppressWarnings("unused")
			Request request = builder.sendRequest(userBeforeUpdate.toString(), new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					Window.alert("Error while updating user");
				}

				public void onResponseReceived(Request request, Response response) {
					if(200 != response.getStatusCode()){
						Window.alert("User updated!");
					}else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		} catch (Exception e) {
			Window.alert("Error while updating user");
		}	
	}

	@Override
	/**
	 * Method to reset user's password
	 */
	public void resetPassword(JSONObject userBeforeReset) {
		String url = Administration.JSON_URL_RESET_PASSWORD;
		url = URL.encode(url);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.POST,url);

		// Make the actual server call.
		try {
			@SuppressWarnings("unused")
			Request request = builder.sendRequest(userBeforeReset.toString(), new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					Window.alert("Error while reset password!");
				}

				public void onResponseReceived(Request request, Response response) {
					if(200 == response.getStatusCode()){
						Window.alert("Changed Password");
					}else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		} catch (Exception e) {
			Window.alert("Error while reset password!");
		}		
	}

	// -----------------------------------------------------------------
	// Delete a user.
	// -----------------------------------------------------------------

	@Override
	/**
	 * Method to delete a user
	 */
	public void delete(JSONObject userBeforeDeletion) {
		String url = Administration.JSON_URL_ADMIN_DEL;
		url = URL.encode(url);
		RequestBuilder builder=new RequestBuilder(RequestBuilder.POST,url);

		// Make the actual server call.
		try {
			@SuppressWarnings("unused")
			Request request = builder.sendRequest(userBeforeDeletion.toString(), new RequestCallback() {
				public void onError(Request request, Throwable exception) {
					Window.alert("Error while deleting user");
				}

				public void onResponseReceived(Request request, Response response) {
					if(200 == response.getStatusCode()){
						Window.alert("User deleted!");
					}else
						ServerResponseMessages.statusCode(response.getStatusCode());
				}
			});
		} catch (Exception e) {
			Window.alert("Error while deleting user");
		}		
	}

	// -----------------------------------------------------------------
	// JSON conversions.
	// -----------------------------------------------------------------

	/**
	 * Convert JSON Users to users Java Object.
	 * @param array
	 * JsonArray to convert from the server 
	 */
	private void convertJSToListUser(JsArray<UserDataJson> array){	
		userList = new ArrayList<User>();
		
		for(int i = 0 ; i < array.length(); i++){
			User user = new User();

			user.setKey(array.get(i).getKey());
			user.setFirstName(array.get(i).getFirstName());
			user.setLastName(array.get(i).getLastName());
			user.setLogin(array.get(i).getLogin());
			user.setEmail(array.get(i).getEmail());
			user.setCredentialLevel(array.get(i).getCredentialLevel());

			userList.add(user);
		}
	}
}
